package com.Filters.Zipfilters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GZIPFilter implements Filter {

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        if (!isCompressionSupported(httpRequest)) {

            chain.doFilter(request, response);

        } else {

            GZIPResponseWrapper gzippedResponse = new GZIPResponseWrapper(httpResponse);
            chain.doFilter(request, gzippedResponse);
            gzippedResponse.close();

        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }

    private boolean isCompressionSupported(HttpServletRequest httpRequest) {
        String encodingHeader = httpRequest.getHeader("Accept-Encoding");
        return encodingHeader.contains("gzip");
    }
}
